package com.lz.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @Package com.lz.config
 * @Project currency-trading
 * @Author lenovo
 * @Date 2022/1/5 23:55
 * @Describe 授权服务器配置类
 * @Version V1.0
 */
@EnableAuthorizationServer //开启授权服务器功能
@Configuration //配置类
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    //使用@Autowired注入报错，需要制作授权管理器
    //密码加密器
    @Autowired
    private PasswordEncoder passwordEncoder;

    //使用@Autowired注入报错，需要制作授权管理器
    //授权管理器
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    //redis连接工厂
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    /**
     * 配置第三方客户端
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("trade-api")     //第三方客户端名称
                .secret(passwordEncoder.encode("trade-secret"))     //第三方客户端密钥
                .scopes("all")     //第三方客户端授权范围
                .accessTokenValiditySeconds(3600)      //token有效期
                .refreshTokenValiditySeconds(7 * 3600);    //refreshToken有效期
        super.configure(clients);
    }

    /**
     * 配设置授权管理器和UserdetailsService
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(redisTokenStore()); //使用redisTokenStore存储token,解决多个authorization-server数据共享问题
        super.configure(endpoints);
    }

    /**
     * TokenStore
     */
    public TokenStore redisTokenStore(){
        return new RedisTokenStore(redisConnectionFactory);
    }
}
